Using sysconf in Ruby with FFI (Update)

2012-10-16

Turns out I was wrong yesterday and what I got was garbage.

So let's do it right today, but unfortunately this is going to be a lot less pretty than I'd hoped for. Also, this is going to use a C compiler in the backround every time you run it. Might be worth caching.

require 'ffi'
require 'ffi/tools/const_generator'

module Sysconf
  extend FFI::Library
  ffi_lib ["c"]

  fcg = FFI::ConstGenerator.new do |gen|
    gen.include 'unistd.h'
    %w[
    _SC_PAGE_SIZE
    _SC_VERSION
    ].each do |const|
      ruby_name = const.sub(/^_SC_/, '').downcase.to_sym
      gen.const(const, "%d", nil, ruby_name, &:to_i)
    end
  end

  CONF = enum(*fcg.constants.map{|_, const|
    [const.ruby_name, const.converted_value]
  }.flatten)

  attach_function :sysconf, [CONF], :long
end


p page_size: Sysconf.sysconf(:page_size)
p version: Sysconf.sysconf(:version)